package com.example.kafka.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

import java.util.Random;

/**
 * @author LiYuhang
 * @version 0.1
 * @application
 * @Date 2021/6/24 18:38
 * @Description TODO
 */
@Component
@Slf4j
public class KafkaProducer {

    @Autowired
    private KafkaTemplate<String, Object> kafkaTemplate;



    public void send(String message) {
        Integer partition=new Random().nextInt(3);
        if(log.isDebugEnabled()){
            log.info("准备发送消息为： partition :{} msg:{}",partition, message);
        }
        //发送消息
        ListenableFuture<SendResult<String, Object>> future = kafkaTemplate.send("test", message);
        future.addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
            @Override
            public void onFailure(Throwable throwable) {
                //发送失败的处理
              log.error("发送失败，{}",throwable.getMessage(),throwable);
            }

            @Override
            public void onSuccess(SendResult<String, Object> stringObjectSendResult) {
                //成功的处理
                log.info(" - 生产者 发送消息成功：" + stringObjectSendResult.toString());
            }
        });


    }


    /**
     * 发送数据demo
     * @param topic
     * @param group
     * @param message
     * @param partition
     */
    public void send(String topic,String group,String message,Integer partition) {

        if(log.isDebugEnabled()){
            log.info("准备发送消息为： partition :{} partition:{} msg:{}",partition, message,partition);
        }

        //发送消息
        ListenableFuture<SendResult<String, Object>> future = kafkaTemplate.send(topic,partition,
                group, message);
        future.addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
            @Override
            public void onFailure(Throwable throwable) {
                //发送失败的处理
                log.info(topic + " - 生产者 发送消息失败：" + throwable.getMessage());
            }

            @Override
            public void onSuccess(SendResult<String, Object> stringObjectSendResult) {
                //成功的处理
                log.info(topic + " - 生产者 发送消息成功：" + stringObjectSendResult.toString());
            }
        });
    }
}
